package JavaCollection;



import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-04 23:20
 * @description 迭代器(设计模式的一种)，用于遍历集合
 *
 * 内部方法：hasNext()、next()
 *
 */
public class IteratorTest {
    @Test
    public void test1(){
        Collection coll=new ArrayList();
        coll.add("AA");
        coll.add("BB");
        coll.add(123);
        coll.add(new Date());
        coll.add(new Person("jerry"));

        Iterator iterator = coll.iterator();
        //方式1：
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        //超出元素个数，抛异常
        //System.out.println(iterator.next());
        //方式2：
        Iterator iterator1 = coll.iterator();
        for (int i=0;i<coll.size();i++){
            System.out.println(iterator1.next());
        }
        //方式3：推荐
        Iterator iterator2 = coll.iterator();
        while(iterator2.hasNext()){
            System.out.println(iterator2.next());
        }
    }

    //测试Iterator中的remove
    @Test
    public void test2(){
        Collection coll=new ArrayList();
        coll.add("AA");
        coll.add("BB");
        coll.add(123);
        coll.add(new Date());
        coll.add(new Person("jerry"));

        Iterator iterator = coll.iterator();

        //remove()方法移除集合中的元素
        while(iterator.hasNext()){
            Object obj=iterator.next();
            if("BB".equals(obj)){
                iterator.remove();
            }
        }
        //注意：必须在next()后调用remove()，且每次next()后只能调一次

        Iterator i2=coll.iterator();
        while(i2.hasNext()){
            System.out.println(i2.next());
        }
    }
}
